package com.ygy.intercptors;

;
import com.ygy.utils.JwtUtil;
import com.ygy.utils.ThreadLocalUtil;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Map;

/**
 * @className: LoginIntercptor
 * @author: Ye
 * @描述: 拦截器
 * 并用 @Component注解把拦截器交给spring的IoC容器
 * @date: 2024/3/11 13:39
 * @version: 1.0
 */
@Component
public class LoginIntercptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证

        // 打印所有请求头
        Enumeration<String> headerNames = request.getHeaderNames();
//        while (headerNames.hasMoreElements()) {
//            String headerName = headerNames.nextElement();
//            String headerValue = request.getHeader(headerName);
//            System.out.println(headerName + ": " + headerValue);
//        }

        //
        // 忽略预检请求
        if ("OPTIONS".equals(request.getMethod())) {
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Token");
            response.setHeader("Access-Control-Max-Age", "3600");
            return true;
        }

        String token = request.getHeader("Token");
//        String token = request.getHeader("Token");
        System.out.println("1232131321"+token);
        try {
            //验证token
            Map<String, Object> claims = JwtUtil.parseToken(token);//不能解析就出错
//            ThreadLocalUtil.set(claims);
            //放行
            return true;
            //怎么是验证成功or失败
        } catch (Exception e) {
            //http响应状态码401
            response.setStatus(401);
            System.out.println(e);


            //不放行
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
